package com.items.Tree;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

public class TreeNodeUtil<E> {
    
    private List<E> boList;

    private Function<E, Boolean> RootNodeFunc;

    private IsParent<E> NodeFunc;

    public TreeNodeUtil(final List<E> boList) {
        this.boList = boList;
    }

    public void setRootNodeFunc(Function<E, Boolean> rootNodeFunc) {
        this.RootNodeFunc = rootNodeFunc;
    }

    public void setNodeFunc(IsParent<E> nodeFunc) {
        this.NodeFunc = nodeFunc;
    }

    /**
     * 获取根节点的列表
     * @param function
     * @return
     */
    private List<E> getRootNode(final Function<E, Boolean> function) {
        final List<E> rootMenuLists = new ArrayList<>();
        for (E menuNode : boList) {
            if (function.apply(menuNode)){
                rootMenuLists.add(menuNode);
            }
        }
        return rootMenuLists;
    }

    /**
     * 建立树形结构
     * @return  List<E>
     */
    public List<E> buildTree(final Customer<E> consumer) {
        final List<E> treeMenus = new ArrayList<>();
        for (E e : getRootNode(RootNodeFunc)) {
            e = buildChildrenTree(e,consumer,NodeFunc);
            treeMenus.add(e);
        }
        return treeMenus;
    }

    /**
     * 递归，建立子树形结构
     * @param pNode
     * @return E
     */
    private E buildChildrenTree(final E pNode, final Customer<E> consumer, final IsParent<E> function) {
        final List<E> childrenMenus = new ArrayList<E>();
        for (E e : boList) {
            if (function.access(pNode,e)) {
                childrenMenus.add(buildChildrenTree(e,consumer,function));
            }
        }
        consumer.access(pNode, childrenMenus);
        return pNode;
    }
}
